﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BLL = KC.Business.MVCMS;
using SQL = KC.DataAccess.Global.SQL;

namespace KC.Presentation.MVCMS
{
	public partial class LiveMonitor : Form
	{
		private string ConnStr = null;
		private bool isUpdating = false;
		private int LastActivityID = 0;

		public LiveMonitor(string connStr) { InitializeComponent(); ConnStr = connStr; }

		private void LiveMonitor_Load(object sender, EventArgs e) 
		{
			tUpdate.Start();
		}

		private async void tUpdate_Tick(object sender, EventArgs e)
		{
			if (!cbLive.Checked || isUpdating) return;
			isUpdating = true;
			DataTable dt = await SQL.ExecuteDataTable(ConnStr, "select top 20 a.ID [Activity], s.ID [Session], i.isSpider, b.domain [Blacklist], a.DateTime, i.address [IP], i.NumProblems Problems, i.Hits, "+
				"	a.UserAgent, sr.Engine, sr.Query, a.Request, a.Referrer from activities a \r\n" +
				"inner join sessions s on a.sid=s.id \r\n" +
				"inner join ips i on s.ipid=i.id \r\n" +
				"left outer join SearchResults sr on sr.aid=a.id \r\n" +
				"left outer join blacklist b on a.referrer like '%' + b.domain+'%' \r\n" +
				"order by a.id desc");

			if (LastActivityID == dt.Select().Max(r => (int)r["Activity"])) return;

			dgActivity.SuspendLayout();
			dgActivity.DataSource = dt;

			// Prepare grid
			LastActivityID = dt.Select().Max(r => (int)r["Activity"]);
			dgActivity.Font = new Font("Calibri", 7);
			dgActivity.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
			dgActivity.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
			for (int i = 0; i < 13; i++)
				dgActivity.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;

			// Adjust column sizes
			dgActivity.Columns["Activity"].Visible = false;
			dgActivity.Columns["Session"].Visible = false;
			dgActivity.Columns["isSpider"].Visible = false;
			dgActivity.Columns["Blacklist"].Visible = false;
			dgActivity.Columns["DateTime"].Width = 70;
			dgActivity.Columns["DateTime"].DefaultCellStyle.Format = "hh:mm:ss tt";
			dgActivity.Columns["IP"].Width = 75;
			dgActivity.Columns["Problems"].Width = 30;
			dgActivity.Columns["Hits"].Width = 40;
			dgActivity.Columns["UserAgent"].Width = 150;
			dgActivity.Columns["Engine"].Width = 50;
			dgActivity.Columns["Query"].Width = 200;
			dgActivity.Columns["Request"].Width = 250;
			dgActivity.Columns["Referrer"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

			// Per row
			for (int i = 0; i < dgActivity.Rows.Count; i++) {
				DataGridViewRow row = dgActivity.Rows[i];
				DataRowView dr = (DataRowView)row.DataBoundItem;

				// Full Row Formats
				if ((int)dr["Activity"] > LastActivityID) // New Activities
					row.DefaultCellStyle.BackColor = Color.LimeGreen;
				else if (((string)dr["IP"]).StartsWith("192.168.")) // Local Activities
					row.DefaultCellStyle.BackColor = Color.LightPink;
				else if ((dr["Blacklist"]).GetType() != typeof(DBNull) && ((string)dr["Blacklist"]).Trim().Length > 0) // Blacklisted
					row.DefaultCellStyle.BackColor = Color.Red;
				else if (((int)dr["Problems"]) > 0) // Problematic IP
					row.DefaultCellStyle.BackColor = Color.Orange;
				else if ((bool)dr["isSpider"]) { // Spiders
					row.DefaultCellStyle.BackColor = Color.Black;
					row.DefaultCellStyle.ForeColor = Color.White; }
				else if (((int)dr["Hits"]) == 1) // New visitors
					row.DefaultCellStyle.BackColor = Color.LightBlue;

				// Partial Row Formats
				if ((dr["Query"]).GetType() != typeof(DBNull) && ((string)dr["Query"]).Trim().Length > 0) {
					row.Cells["Query"].Style.BackColor = Color.LightGreen;
					row.Cells["Query"].Style.ForeColor = Color.Black; }
				else if ((dr["Referrer"]).GetType() != typeof(DBNull) && ((string)dr["Referrer"]).Trim().Length > 0) {
					row.Cells["Referrer"].Style.BackColor = Color.LightGreen;
					row.Cells["Referrer"].Style.ForeColor = Color.Black; } }

			dgActivity.ResumeLayout(true);
			isUpdating = false;
		}
	}
}
